﻿using CommonBase;
using CommonBase.ResponseBase;
using CustomControls.PoptipCtr;
using CustomControls.PoptipCtr.Base;
using LogProjectManager;
using ManagementToolClient.BaseViewModels;
using ManagementToolClient.Models;
using ManagementToolClient.PageDeclaration;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ManagementToolClient.ViewModels
{
    internal class DeviceManagerViewModel : BaseViewModel
    {
        private string CompanyId { set; get; }


        private ObservableCollection<DeviceManagerModel> _DeviceList = new ObservableCollection<DeviceManagerModel>();
        public ObservableCollection<DeviceManagerModel> DeviceList
        {
            get { return _DeviceList; }
            set { SetProperty(ref _DeviceList, value); }
        }


        private DeviceManagerModel _DeviceManagerItem;
        public DeviceManagerModel DeviceManagerItem
        {
            get { return _DeviceManagerItem; }
            set { 
                SetProperty(ref _DeviceManagerItem, value);
                GetTargetDeviceModule(value.robatmac);
            }
        }


        private ObservableCollection<DeviceModeuleManagerModel> _DeviceModeuleList = new ObservableCollection<DeviceModeuleManagerModel>();
        public ObservableCollection<DeviceModeuleManagerModel> DeviceModeuleList
        {
            get { return _DeviceModeuleList; }
            set { SetProperty(ref _DeviceModeuleList, value); }
        }

        #region cmd
        private DelegateCommand<DeviceManagerModel> _EditDeviceCommand;
        public DelegateCommand<DeviceManagerModel> EditDeviceCommand =>
            _EditDeviceCommand ?? (_EditDeviceCommand = new DelegateCommand<DeviceManagerModel>(ExcuteEditDeviceCommand));

     

        private DelegateCommand<DeviceManagerModel> _DeletetDeviceCommand;
        public DelegateCommand<DeviceManagerModel> DeletetDeviceCommand =>
            _DeletetDeviceCommand ?? (_DeletetDeviceCommand = new DelegateCommand<DeviceManagerModel>(ExcuteDeletetDeviceCommand));


        private DelegateCommand<DeviceManagerModel> _AddDeviceModuleCommand;
        public DelegateCommand<DeviceManagerModel> AddDeviceModuleCommand =>
            _AddDeviceModuleCommand ?? (_AddDeviceModuleCommand = new DelegateCommand<DeviceManagerModel>(ExcuteAddDeviceModuleCommand));


        private DelegateCommand<DeviceModeuleManagerModel> _UploadModuleFileCommand;
        public DelegateCommand<DeviceModeuleManagerModel> UploadModuleFileCommand =>
            _UploadModuleFileCommand ?? (_UploadModuleFileCommand = new DelegateCommand<DeviceModeuleManagerModel>(ExcuteUploadModuleFileCommand));

    




        #endregion

        public DeviceManagerViewModel(IContainerExtension container) : base(container)
        {

        }

        private void ExcuteEditDeviceCommand(DeviceManagerModel model)
        {
          
        }

        private void ExcuteDeletetDeviceCommand(DeviceManagerModel model)
        {
            Task.Run(async () => {
                try
                {
                    var url = "http://127.0.0.1:8081"+ "/api/ToDeleteDevice?" + $"_uuid={model.uuid}";
                  

                    
                    var httpClient = new System.Net.Http.HttpClient();


                    HttpContent content = new StringContent("", Encoding.UTF8, "application/json");

                    var response = httpClient.PostAsync(url, content).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        var _itemResult = JsonConvert.DeserializeObject<AuthorizationCodeResponseBody>(responseBody);

                        if (_itemResult.code == ((int)ErrorCode.OK).ToString())
                        {
                            Application.Current.Dispatcher.Invoke(() => {
                                DeviceList.Remove(model);
                            });
                        }

                        else
                        {
                            LogManager.WriteLog(LogTypeEnum.Normal, "GetDate", "访问接口异常,data为空");
                        }

                    }
                    else
                    {
                        LogManager.WriteLog(LogTypeEnum.Exception, "GetDate", "接口访问失败");
                    }
                }
                catch (Exception ex)
                {
                    LogManager.WriteLog(LogTypeEnum.Exception, "GetDate", ex.Message);
                }
            });
        }

        private void ExcuteAddDeviceModuleCommand(DeviceManagerModel model)
        {
            LayDialogParameter _dialogParameter = new LayDialogParameter();
            _dialogParameter.Add("uuid", model.uuid);
            LayDialogControl.ShowDialog(SystemResourceExten.Nav_AddDeviceModulePage, _dialogParameter, rest =>
            {
                switch (rest.Result)
                {
                    case ButtonResult.Yes:
                        MessageControl.Warning("添加成功!", "RootMessageTooken");
                        GetTargetDeviceModule(DeviceManagerItem.robatmac);
                        break;
                    case ButtonResult.No:

                        break;
                    case ButtonResult.Default:
                        break;
                    default:
                        break;
                }
            }, SystemResource.Nav_RootDialogTooken);
        }


        private void ExcuteUploadModuleFileCommand(DeviceModeuleManagerModel model)
        {
            LayDialogParameter _dialogParameter = new LayDialogParameter();
            _dialogParameter.Add("ModuleID", model.moduleid);
            _dialogParameter.Add("DeviceID", DeviceManagerItem.uuid);
            LayDialogControl.ShowDialog(SystemResourceExten.Nav_AddUpdateFile, _dialogParameter, rest =>
            {
                switch (rest.Result)
                {
                    case ButtonResult.Yes:
                        MessageControl.Warning("上传成功!", "RootMessageTooken");
                        GetTargetDeviceModule(DeviceManagerItem.robatmac);
                        break;
                    case ButtonResult.No:

                        break;
                    case ButtonResult.Default:
                        break;
                    default:
                        break;
                }
            }, SystemResource.Nav_RootDialogTooken);
        }

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            if (navigationContext.Parameters.ContainsKey("companyid")) 
            {
                CompanyId = navigationContext.Parameters["companyid"].ToString();
            }
           
        }

        public override void ExecuteUnLoadedCommand()
        {
            base.ExecuteUnLoadedCommand();
        }

        public override void ExecuteLoadedCommand()
        {
            base.ExecuteLoadedCommand();
            GetDate();
        }

        private async void GetDate()
        {
            DeviceList.Clear();
            await Task.Run(async () => {
                try
                {
                    var url = "http://127.0.0.1:8081" ;
                    if (string.IsNullOrEmpty(CompanyId))
                    {
                        url += "/api/ToGetAllDeviceByPage?";
                    }
                    else 
                    {
                        url += "/api/ToGetDeviceByCompanyId?";
                        url += $"_companyid={CompanyId}";
                    }

                    url += "&" + $"inputpageCode=1" + "&" + $"inputPageSize=1000";
                    var httpClient = new System.Net.Http.HttpClient();


                    var response = httpClient.GetAsync(url).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        var _itemResult = JsonConvert.DeserializeObject<AuthorizationCodeResponseBody>(responseBody);

                        if (_itemResult.code == ((int)ErrorCode.OK).ToString())
                        {
                            if (_itemResult.Data != null)
                            {
                                var itemList = JsonConvert.DeserializeObject<List<DeviceManagerModel>>(_itemResult.Data.ToString());
                                if (itemList.Count > 0)
                                {
                                    foreach (var item in itemList)
                                    {
                                        Application.Current.Dispatcher.Invoke(() => {
                                            DeviceList.Add(item);
                                        });
                                    }
                                }
                            }
                        }

                        else
                        {
                            LogManager.WriteLog(LogTypeEnum.Normal, "GetDate", "访问接口异常,data为空");
                        }

                    }
                    else
                    {
                        LogManager.WriteLog(LogTypeEnum.Exception, "GetDate", "接口访问失败");
                    }
                }
                catch (Exception ex)
                {
                    LogManager.WriteLog(LogTypeEnum.Exception, "GetDate", ex.Message);
                }
            });
            if (DeviceList.Count>0) 
            {
                DeviceManagerItem = DeviceList.FirstOrDefault();
            }
        }


        private void GetTargetDeviceModule(string _robatMac) 
        {
            DeviceModeuleList.Clear();
            Task.Run(async () => {
                try
                {
                    var url = "http://127.0.0.1:8081/api/ToGetNeedDownModule?" + $"_robatMac={_robatMac}";
          
                    var httpClient = new System.Net.Http.HttpClient();


                    var response = httpClient.GetAsync(url).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        var _itemResult = JsonConvert.DeserializeObject<AuthorizationCodeResponseBody>(responseBody);

                        if (_itemResult.code == ((int)ErrorCode.OK).ToString())
                        {
                            if (_itemResult.Data != null)
                            {
                                var itemList = JsonConvert.DeserializeObject<List<DeviceModeuleManagerModel>>(_itemResult.Data.ToString());
                                if (itemList.Count > 0)
                                {
                                    foreach (var item in itemList)
                                    {
                                        Application.Current.Dispatcher.Invoke(() => {
                                            DeviceModeuleList.Add(item);
                                        });
                                    }
                                }
                            }
                        }

                        else
                        {
                            LogManager.WriteLog(LogTypeEnum.Normal, "GetDate", "访问接口异常,data为空");
                        }

                    }
                    else
                    {
                        LogManager.WriteLog(LogTypeEnum.Exception, "GetDate", "接口访问失败");
                    }
                }
                catch (Exception ex)
                {
                    LogManager.WriteLog(LogTypeEnum.Exception, "GetDate", ex.Message);
                }
            });
        }
    }
}
